package com.handu.luna.boss.controller;



import java.io.UnsupportedEncodingException;
import java.util.Base64;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import com.handu.luna.core.domain.search.BrandSearch;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.handu.luna.core.domain.BossException;
import com.handu.luna.core.domain.goods.Brand;


@Controller
@RequestMapping("/goods/brand/*")
public class BrandController extends BaseController {
	/**
	 * 翻页
	 * @param viewState 需对其进行拆解 最后也需返回
	 * @param pageable
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(method=RequestMethod.GET)
	public BossModel index(String viewState,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = {"createdDate"},direction = Sort.Direction.ASC) Pageable pageable) throws UnsupportedEncodingException{
		BrandSearch brandSearch;
        if (StringUtils.isNotBlank(viewState) && !viewState.equals("-1")){
            brandSearch = (BrandSearch)JSONObject.toBean(JSONObject.fromObject(new String(Base64.getUrlDecoder().decode(viewState),"UTF-8")), BrandSearch.class);
            return createModel()
                    .add("brandsPage",context.getBrandRepository().findAll(Brand.searchCondition(brandSearch),pageable))
                    .add("brandSearch", brandSearch)
                    .add("viewState", viewState)
                    .add("brandTypes", Brand.BrandType.values());
        }else{
            brandSearch = new BrandSearch();
            return createModel()
                    .add("brandsPage",context.getBrandRepository().findAll(pageable))
                    .add("brandSearch", brandSearch)
                    .add("viewState", "")
                    .add("brandTypes", Brand.BrandType.values());
        }
	}
	/**
	 * 点击click查询  返回的时候需对查询参数封装 方便翻页传参  翻页处理对参数进行拆解
     * @param brandSearch
	 * @param pageable
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(method=RequestMethod.POST)
	public BossModel index(BrandSearch brandSearch,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = {"createdDate"},direction = Sort.Direction.ASC) Pageable pageable) throws UnsupportedEncodingException{
        return createModel()
                .add("brandsPage",context.getBrandRepository().findAll(Brand.searchCondition(brandSearch),pageable))
                .add("brandSearch", brandSearch)
                .add("viewState", Base64.getUrlEncoder().encodeToString(JSONObject.fromObject(brandSearch).toString().getBytes("UTF-8")))
                .add("brandTypes", Brand.BrandType.values());
	}
	/**
	 * 删除掉需判断是否该页还有数据 防止AOP调用再次进行删除操作 所以使用重定向 让AOP去处理index 而不是处理delete
	 * 其余的模块的删除未加入pageNumber* AOP的处理
	 * @param viewState
	 * @param id
	 * @param pageable
	 * @param redirectAttributes
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value="delete",method= RequestMethod.POST)
	public BossModel delete(String viewState,long id,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = {"createdDate"},direction = Sort.Direction.ASC) Pageable pageable,
			RedirectAttributes redirectAttributes) throws UnsupportedEncodingException{
		//此处需加入判断 该品牌下是否有商品或者品牌通用信息  若有则不能删除
		if(context.getGoodsRepository().has("brandId", id)){
			throw new BossException(context.getBrandRepository().findOne(id).getName()+"品牌下还有商品，删除前请先将该品牌下的商品移植别的品牌！");
		}
		context.getBrandRepository().findOne(id).delete();
		redirectAttributes.addAttribute("page", pageable.getPageNumber());
		//为了能匹配index/{viewState} 此处必须给viewstate初始化 并在validation()方法处加入相应判断
		return createModel("redirect:index/"+(validation(viewState)?viewState:-1));
	}
	/**
	 * 删除后调用 避免分页之后切面调用再次进行删除操作
	 * @param viewState
	 * @param pageable
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value="index/{viewState}")
	public BossModel index(@PathVariable String viewState,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = {"createdDate"},direction = Sort.Direction.ASC) Pageable pageable,
			HttpServletRequest request) throws UnsupportedEncodingException{
        BrandSearch brandSearch;
        if (StringUtils.isNotBlank(viewState) && !viewState.equals("-1")){
            brandSearch = (BrandSearch)JSONObject.toBean(JSONObject.fromObject(new String(Base64.getUrlDecoder().decode(viewState),"UTF-8")), BrandSearch.class);
            return createModel("goods/brand/brands_table")
                    .add("brandsPage",context.getBrandRepository().findAll(Brand.searchCondition(brandSearch),pageable))
                    .add("viewState", viewState);
        }else{
            return createModel("goods/brand/brands_table")
                    .add("brandsPage",context.getBrandRepository().findAll(pageable))
                    .add("viewState", "");
        }
	}
	
	@RequestMapping(value="edit/{id}")
	public BossModel edit(@PathVariable long id,int page,String viewState){
		return createModel("goods/brand/save")
                .add("brand",context.getBrandRepository().findOne(id))
                .add("brandTypes", Brand.BrandType.values())
                .add("page", page)
                .add("viewState", (viewState == null ? "" : viewState));
	}
	
	
	@RequestMapping(value="add")
	public BossModel add(int page,String viewState){
		return createModel("goods/brand/save")
                .add("brand",new Brand())
                .add("brandTypes", Brand.BrandType.values())
                .add("page", page)
                .add("viewState", (viewState == null ? "" : viewState));
	}
	
	
	@RequestMapping(value="save",method = RequestMethod.POST)
	@InitBinder(value={"name","url","keyWord","logo","description","displayOrder","type","displayed","story"})
	public BossModel save(@Valid final Brand brand, final BindingResult bindingResult, final ModelMap model,
			RedirectAttributes redirectAttributes,
            int page,String viewState){
		if (bindingResult.hasErrors()) {
			return createModel("goods/brand/save").add("brand",brand).add("brandTypes", Brand.BrandType.values());
		}
		String message = "";
		if(null==brand.getId() || brand.getId() == 0){
			message = "添加品牌"+brand.getName()+ "成功";
		}else{
			message = "修改品牌"+brand.getName()+ "成功";
		}
		if (!(brand.getId()==null||brand.getId()==0)){
            redirectAttributes.addAttribute("page",page);
            redirectAttributes.addAttribute("viewState", StringUtils.isNotBlank(viewState)?viewState:"");
        }
		context.getBrandRepository().save(brand);
		redirectAttributes.addFlashAttribute("message", message);
		
		return createModel("redirect:index");
	}
	
	@RequestMapping(value="error")
	public void error(){
		throw new BossException("test");
	}
	
	@RequestMapping(value="verifyName")
	public @ResponseBody boolean verifyName(Brand brand,String brandId){
		int num = context.getBrandRepository().findByNameLike(brand.getName()).size();
		if(num != 0){
			if(validation(brandId)){
				if(context.getBrandRepository().findOne(Long.parseLong(brandId)).getName().equals(brand.getName())){
					return true;
				}else{
					return false;
				}
			}else{
				return false;
			}
		}else{
			return true;
		}
	}

	/**
	 * 后期进行自己扩展  可单独写一个验证类
	 * 对于String类型的参数  不为空且不是空字符串
	 * 对于list
	 * @param obj
	 * @return
	 */
	private boolean validation(Object obj){
		if(obj instanceof String){
			obj = (String)obj;
			return obj != null && !obj.equals("");
		}else{
			return false;
		}
	}
}
